/**
 * @author:linjiye
 * @date: 2025/1/7
 * @desc:
 **/

import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import React, {useCallback, useEffect, useState} from 'react'
import FormTitle from "@/components/FormTitle";
import {Badge, Flex} from "@ant-design/react-native";
import FcButton from "@/components/FcButton";
import FcTextInput from "@/components/FcTextInput";
import useGetStorage from "@/hooks/useGetStorage";
import {
    useAnalysisCustomerStrMutation, useAnalysisMutation,
    useProfitModelInfoMutation,
    useProfitModelMutation
} from "@/store/api/aiFeeding/aiFeedingApi";
import {useLocalSearchParams} from "expo-router";
import {useDispatch, useSelector} from "react-redux";
import {set_productId, set_selectItem} from "@/store/reducer/aiFeeding/aiFeedingSlice";
import Loading from "@/components/Loading";

type Props = {}

const contentFeed = ({synchronize}: Props) => {
    const {id} = useLocalSearchParams()

    const [selectItem, setSelectItem] = useState()
    const [client, setClient] = useState('')
    const [introduce, setIntroduce] = useState('')

    const [profitList,setProfitList] = useState([])
    const [productId,setProductId] = useState('')

    const [khLoading, setKhLoading] = useState(false)
    const [jsLoading, setJSLoading] = useState(false)

    const [profitModelInfoFun] = useProfitModelInfoMutation()
    // const [profitModelFun] = useProfitModelMutation()
    const [analysisCustomerStrFun] = useAnalysisCustomerStrMutation()
    const [analysisFun] = useAnalysisMutation()

    const dispatch = useDispatch();
    // const sliceProductId = useSelector(state => state.aiFeeding.productId)
    // const sliceSelectItem = useSelector(state => state.aiFeeding.selectItem)

    const getProfitList = useCallback(() => {
        useGetStorage('loginData').then(res => {
            let list = res?.sysAllDictItems?.profit_model || []
            setProfitList(list)
            let p = {
                ...list[0],
                productCustomer: '',
                productCustomerOld: '',
                productInformation: '',
                productInformationOld:'',
                groupId: '',
                id: ''
            }
            setSelectItem(p)
            getProfitModelInfo(id,list)

            dispatch(set_selectItem(p))
        })
    },[id])

    useEffect(() => {
        if(synchronize) {
            getProfitList()
        }
    }, [synchronize]);

    useEffect(() => {
        getProfitList()
        if(id) {
            setProductId(id)
            dispatch(set_productId(id))
        }

    }, [id]);

    function getProfitModelInfo(id,pList) {
        profitModelInfoFun({id}).then(res => {
            if(res.data.code === 200) {
                let list = res.data.result || []

                if(list.length == 0) {
                    return
                }


                // let pList = [...profitList]
                pList.map(item => {
                    item.productCustomer = ''
                    item.productCustomerOld = ''
                    item.productInformation = ''
                    item.productInformationOld = ''
                    item.groupId = ''
                    item.id = ''

                    list.map(item2 => {
                        if(item.value == item2.typeKey) {
                            item.data = item2
                            item.productCustomer = item2.productCustomer || ''
                            item.productCustomerOld = item2.productCustomer || ''
                            item.productInformation = item2.productInformation || ''
                            item.productInformationOld = item2.productInformation || ''
                            item.groupId = item2.groupId || ''
                            item.id = item2.id || ''
                        }
                    })
                })

                let index = pList.findIndex(item => item.value == list[0].typeKey)

                dispatch(set_selectItem(pList[index]))

                setSelectItem(pList[index])
                setProfitList(pList)
            }
        })
    }


    function handleSelectProfit(val) {
        let obj = {
            ...val,
            productCustomer: val.productCustomerOld,
            productInformation: val.productInformationOld,
        }
        setSelectItem(obj)
        dispatch(set_selectItem(obj))
    }

    function handleGetProductInformation(val) {
        let obj = {
            ...selectItem,
            productInformation:val
        }
        setSelectItem(obj)
        dispatch(set_selectItem(obj))
    }

    function handleGetProductCustomer(val) {
        console.log(val);
        let obj = {
            ...selectItem,
            productCustomer:val
        }
        setSelectItem(obj)
        dispatch(set_selectItem({obj}))
    }

    function onblurOfcustomer() {
        // if(selectItem?.productCustomer === selectItem?.productCustomerOld && selectItem?.productInformation === selectItem?.productInformationOld) {
        //     return
        // }
        //
        // profitModelFun({
        //     productCustomer:selectItem?.productCustomer,
        //     productInformation:selectItem?.productInformation,
        //     groupId:selectItem?.groupId || productId,
        //     status: 1,
        //     typeKey:selectItem?.value,
        // }).then(res => {
        //     console.log(res);
        //     // if(res.data.code === 200) {
        //     //     getProfitModelInfo(productId,profitList)
        //     // }
        // })
    }

    function handleAnalysisCustomerStr() {
        setKhLoading(true)
        analysisCustomerStrFun({
            id:productId,
            operationMode: selectItem?.value,
        }).then(res => {
            if(res?.data?.code === 200) {
                setSelectItem({...selectItem,productCustomer:res.data?.result?.productCustomer})
                dispatch(set_selectItem({selectItem}))
            }
            setKhLoading(false)
        }).catch(err => {
            setKhLoading(false)
        })
    }

    function handleAnalysis() {
        setJSLoading(true)
        analysisFun({
            id:productId,
            operationMode: selectItem?.value,
            productCustomer:selectItem?.productCustomer,
        })  .then(res => {
            if(res?.data?.code === 200) {
                let obj = {
                    ...selectItem,
                    productInformation:res.data?.result?.productInformation
                }
                setSelectItem(obj)
                dispatch(set_selectItem(obj))
            }
            setJSLoading(false)
        }).catch(err => {
            setJSLoading(false)
        })
    }

    return (
        <View style={{paddingHorizontal: 16}}>
            <FormTitle title='手动输入资料' isLeftIcon titleHint={'*'}
                       titleHintStyle={styles.hint}/>
            <Flex wrap='wrap' style={{marginLeft: -5}}>
                {profitList.map((item, index) =>
                    // <Badge text={item?.data?.id ? '' : '未填写'} key={index}>
                        <FcButton
                             onClick={() => handleSelectProfit(item)}
                            style={[styles.btn_item, selectItem.value === item.value && styles.btn_bg_active]}
                            itemStyle={[{
                                fontSize: 14,
                                padding: 0
                            }, ]}
                             itemTextStyle={[selectItem.value === item.value && styles.btn_txt_active]}
                            textName={item.label}
                             positionEle={
                                <>
                                    {!item?.data?.id &&
                                        <View style={styles.badge_wrap}>
                                            <Text style={{color: 'white',fontSize:6}}>未填写</Text>
                                        </View>
                                    }
                                </>
                             }
                        ></FcButton>
                    // </Badge>
                )}
            </Flex>
            <FormTitle title='客户是谁' isLeftIcon titleHint={'*'}
                       titleHintStyle={styles.hint} style={{paddingTop: 32}}/>
            <FcTextInput multiline text={selectItem?.productCustomer} placeholder='购买你产品或服务的人'
                         onChangeText={(val) => handleGetProductCustomer(val)}
                         onblur={() => onblurOfcustomer()}
                         height={96}
                         closeBtnStyle={{right: 92}}
                         positionEle={
                             <>
                                 <View style={styles.ai_btn}>
                                     <FcButton
                                         onClick={() => handleAnalysisCustomerStr()}
                                         disable={khLoading}
                                         type='BjJB'
                                         colors={['#6989FF', '#C65EFD']}
                                         style={{width: 75, height: 28}}
                                         itemStyle={{borderRadius: 8, fontSize: 12}}
                                         textName={khLoading?'AI编写中':'AI编写'}
                                         btnLeftEle={
                                             <Text style={{
                                                 fontFamily: 'FcIconFont',
                                                 fontSize: 16,
                                                 color: 'white'
                                             }}>&#xe63d;</Text>
                                         }
                                     />
                                 </View>
                                {!selectItem?.productCustomer && khLoading &&  <Loading style={styles.loading} iconStyle={{width:40,height:40}} text={'AI编写中'}/>}
                             </>
                         }
            />
            <FormTitle title='产品介绍' isLeftIcon titleHint={'*'}
                       titleHintStyle={styles.hint} style={{paddingTop: 32}}/>
            <FcTextInput multiline text={selectItem?.productInformation}
                         placeholder='你可以介绍服务功能、服务卖点、使用场景资质证书、售后保障等'
                         onChangeText={(val) => handleGetProductInformation(val)}
                         onblur={() => onblurOfcustomer()}
                         height={200}
                         style={{textAlign: 'top'}}
                         closeBtnStyle={{right: 92}}
                         positionEle={
                             <>
                                 <View style={styles.ai_btn}>
                                     <FcButton
                                         onClick={() => handleAnalysis()}
                                         type='BjJB'
                                         colors={['#6989FF', '#C65EFD']}
                                         style={{width: 75, height: 28}}
                                         itemStyle={{borderRadius: 8, fontSize: 12}}
                                         textName={jsLoading?'AI编写中':'AI编写'}
                                         disable={!selectItem?.productCustomer || jsLoading }
                                         btnLeftEle={
                                             <Text style={{
                                                 fontFamily: 'FcIconFont',
                                                 fontSize: 16,
                                                 color: 'white'
                                             }}>&#xe63d;</Text>
                                         }
                                     />
                                 </View>
                                 {!selectItem?.productInformation && jsLoading &&  <Loading style={styles.loading} iconStyle={{width:40,height:40}} text={'AI编写中'}/>}
                             </>
                         }
            />
        </View>
    )
}

export default contentFeed

const styles = StyleSheet.create({
    btn_item: {
        paddingHorizontal: 16,
        paddingVertical: 5,
        borderRadius: 20,
        backgroundColor: '#F1F2F4',
        marginHorizontal: 5,
        marginBottom: 8,
        color: '#79797A'
    },
    btn_txt_active: {
        color: '#2856FF',
    },
    btn_bg_active: {
        backgroundColor: 'rgba(40, 86, 255, 0.1)'
    },
    hint: {
        color: '#FA5151', fontSize: 14, marginLeft: 3
    },
    ai_btn: {
        width: 69,
        height: 28,
        position: "absolute",
        right: 16,
        bottom: 8
    },
    badge_wrap: {
        position: "absolute",
        right: -10,
        top: -4,
        backgroundColor: '#FA5151',
        borderRadius: 20,
        paddingHorizontal: 4,
        paddingVertical: 2,
        zIndex: 100
    },
    loading:{
        position:'absolute',
        right:0,
        top:0,
        zIndex:10,
        backgroundColor:'transparent',
    }
})